package csv;

import domain.Student;

import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Description
 *
 * @ClassName csv
 * @Copyright 炫彩互动
 * @Author yanglh
 * @Create Date  2016/6/22
 * @Modified by none
 * @Modified Date
 */

public class Bean2Map {
    public static void main(String[] args) throws Exception {
        Student student = new Student();
        student.setSid(1000);
        student.setSname("杨鲁华");
        Map map = Bean2Map.convetBean2Map(student);
        for(Object entry : map.entrySet()){
            Map.Entry entry1  = (Map.Entry)entry;
            Object key = entry1.getKey();
            Object value = entry1.getValue();
            System.out.println(key+":"+value);
        }
    }

    //通过反射将对象装换成map
    public static LinkedHashMap<Object, Object> convetBean2Map(Object obj) throws Exception {
        LinkedHashMap<Object, Object> resultMap = new LinkedHashMap<Object, Object>();
        Class clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        int count = 1;
        for(Field field:fields){
            field.setAccessible(true);
            Object value = field.get(obj);
            resultMap.put(count++,value);
        }
        return resultMap;
    }
}
